<template>
  <div ref="editorContainer" class="quill-editor"></div>
</template>

<script>
import {ref, onMounted, onBeforeUnmount, watch} from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';

export default {
  name: 'QuillEditor',
  props: {
    modelValue: {
      type: String,
      default: '',
    },
  },
  setup(props, {emit}) {
    const editorContainer = ref(null);
    let quill;

    const initializeEditor = () => {
      quill = new Quill(editorContainer.value, {
        theme: 'snow',
        modules: {
          toolbar: [
            [{'header': [1, 2, false]}],
            ['bold', 'italic', 'underline'], // 加粗.
            [{'color': []}, {'background': []}], // 颜色、背景
            [{'list': 'ordered'}, {'list': 'bullet'}], // 列表
            ['blockquote'], // 代码段
            ['link', 'image'], // 图片、链接
            ['clean'], // 清除样式
          ],
        },
      });

      quill.on('text-change', () => {
        emit('update:modelValue', quill.root.innerHTML);
      });

      // 设置初始值
      quill.root.innerHTML = props.modelValue;
    };

    onMounted(() => {
      if (editorContainer.value) {
        initializeEditor();
      }
    });

    watch(
      () => props.modelValue,
      (newValue) => {
        if (quill && quill.root.innerHTML !== newValue) {
          quill.root.innerHTML = newValue;
        }
      }
    );

    const destroyEditor = () => {
      if (quill) {
        quill.off('text-change'); // 解绑事件
        quill = null; // 确保 Quill 实例不再存在
        editorContainer.value.innerHTML = ""; // 清空容器
      }
    };

    onBeforeUnmount(() => {
      destroyEditor();
    });

    return {
      editorContainer,
    };
  },
};
</script>

<style scoped>

</style>
